package com.ruoyi.web.controller.module.wx;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.PageUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.domain.module.property.Property;
import com.ruoyi.system.domain.module.wx.UserIntegralRecord;
import com.ruoyi.system.domain.module.excel.IntegralRecordExcel;
import com.ruoyi.system.service.module.estate.IEstateService;
import com.ruoyi.system.service.module.property.IPropertyService;
import com.ruoyi.system.service.module.wx.IUserIntegralRecordService;
import com.ruoyi.web.controller.common.BaseController;
import lombok.RequiredArgsConstructor;
import javax.validation.constraints.*;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.validation.annotation.Validated;
import com.ruoyi.common.annotation.RepeatSubmit;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.validate.AddGroup;
import com.ruoyi.common.core.validate.EditGroup;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.core.page.TableDataInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 * 用户的积分记录Controller
 *
 * @author ruoyi
 * @date 2021-08-11
 */
@Validated
@Api(value = "用户的积分记录控制器", tags = {"用户的积分记录管理"})
@RequiredArgsConstructor(onConstructor_ = @Autowired)
@RestController
@RequestMapping("/module/integral/record")
public class UserIntegralRecordController extends BaseController {

    private final IUserIntegralRecordService userIntegralRecordService;
    private final IPropertyService propertyService;
    private final IEstateService estateService;

    /**
     * 查询用户的积分记录列表
     */
    @ApiOperation("查询用户的积分记录列表")
    @PreAuthorize("@ss.hasPermi('module:integralrecord:list')")
    @GetMapping("/list")
    public TableDataInfo<UserIntegralRecord> list(@Validated UserIntegralRecord userIntegralRecord) {
        SysUser sysUser = getUser();
		QueryWrapper<UserIntegralRecord> qw = new QueryWrapper<>();
		qw.eq("get_type",userIntegralRecord.getGetType());

        if(sysUser.getUserType() == 2){//物业公司
            qw.eq("property_id",sysUser.getPropertyId());
        } else if(sysUser.getUserType() == 3){//小区
            qw.eq("estate_id",sysUser.getEstateId());
        }

		if(StrUtil.isNotEmpty(userIntegralRecord.getPhoneNum())){
			qw.eq("phone_num",userIntegralRecord.getPhoneNum());
		}

		if(StrUtil.isNotEmpty(userIntegralRecord.getPayNo())){
			qw.eq("pay_no",userIntegralRecord.getPayNo());
		}

		if(StrUtil.isNotEmpty(userIntegralRecord.getBeginDate())){
			qw.between("create_time",userIntegralRecord.getBeginDate() + " 00:00:00",userIntegralRecord.getEndDate() + " 23:59:59");
		}
		qw.orderByDesc("create_time");
        TableDataInfo<UserIntegralRecord> td = PageUtils.buildDataInfo(userIntegralRecordService.page(PageUtils.buildPage(),qw));
		List<UserIntegralRecord> list = td.getRows();
		list.forEach(record ->{
            Property property = propertyService.findById(record.getPropertyId());
            if(property!=null){
                record.setPropertyName(property.getPropertyName());
            }
        });
        return td;
    }


    /**
     * 导出用户的积分记录列表
     */
    @ApiOperation("导出用户的积分记录列表")
    @PreAuthorize("@ss.hasPermi('module:integralrecord:export')")
    @Log(title = "用户的积分记录", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult<UserIntegralRecord> export(@Validated UserIntegralRecord userIntegralRecord) {
        SysUser sysUser = getUser();
        QueryWrapper<UserIntegralRecord> qw = new QueryWrapper<>();
        qw.eq("get_type",userIntegralRecord.getGetType());
        if(StrUtil.isNotEmpty(userIntegralRecord.getPhoneNum())){
            qw.eq("phone_num",userIntegralRecord.getPhoneNum());
        }

        if(sysUser.getUserType() == 2){//物业公司
            qw.eq("property_id",sysUser.getPropertyId());
        } else if(sysUser.getUserType() == 3){//小区
            qw.eq("estate_id",sysUser.getEstateId());
        }
        if(StrUtil.isNotEmpty(userIntegralRecord.getPayNo())){
            qw.eq("pay_no",userIntegralRecord.getPayNo());
        }

        if(StrUtil.isNotEmpty(userIntegralRecord.getBeginDate())){
            qw.between("create_time",userIntegralRecord.getBeginDate() + " 00:00:00",userIntegralRecord.getEndDate() + " 23:59:59");
        }
        List<UserIntegralRecord> list = userIntegralRecordService.list(qw);
        if(CollUtil.isNotEmpty(list)){
            for (UserIntegralRecord record : list){
                record.setCreateTimeStr(DateUtils.getTime(record.getCreateTime()));
            }
        }
        ExcelUtil<UserIntegralRecord> util = new ExcelUtil<>(UserIntegralRecord.class);
        return util.exportExcel(list, "用户的积分记录");
    }


    /**
     * 导出用户的积分记录列表
     */
    @ApiOperation("导出用户的积分记录列表")
    @PreAuthorize("@ss.hasPermi('module:integralrecord:export')")
    @Log(title = "用户的积分记录", businessType = BusinessType.EXPORT)
    @GetMapping("/exportTotal")
    public AjaxResult<IntegralRecordExcel> exportTotal(@Validated UserIntegralRecord userIntegralRecord) {
        Map<String,Object> map = new HashMap<>();
        if(StrUtil.isNotEmpty(userIntegralRecord.getBeginDate())){
            map.put("begin_time",userIntegralRecord.getBeginDate() + " 00:00:00");
            map.put("end_time",userIntegralRecord.getEndDate() + " 23:59:59");
        }
        List<IntegralRecordExcel> list = userIntegralRecordService.selectTotalByTime(map);
        ExcelUtil<IntegralRecordExcel> util = new ExcelUtil<>(IntegralRecordExcel.class);
        return util.exportExcel(list, "消费记录导出");
    }

    /**
     * 获取用户的积分记录详细信息
     */
    @ApiOperation("获取用户的积分记录详细信息")
    @PreAuthorize("@ss.hasPermi('module:integralrecord:query')")
    @GetMapping("/{id}")
    public AjaxResult<UserIntegralRecord> getInfo(@NotNull(message = "主键不能为空") @PathVariable("id") Long id) {
        return AjaxResult.success(userIntegralRecordService.getById(id));
    }

    /**
     * 新增用户的积分记录
     */
    @ApiOperation("新增用户的积分记录")
    @PreAuthorize("@ss.hasPermi('module:integralrecord:add')")
    @Log(title = "用户的积分记录", businessType = BusinessType.INSERT)
    @RepeatSubmit
    @PostMapping()
    public AjaxResult<Void> add(@Validated(AddGroup.class) @RequestBody UserIntegralRecord userIntegralRecord) {
        return toAjax(userIntegralRecordService.save(userIntegralRecord) ? 1 : 0);
    }

    /**
     * 修改用户的积分记录
     */
    @ApiOperation("修改用户的积分记录")
    @PreAuthorize("@ss.hasPermi('module:integralrecord:edit')")
    @Log(title = "用户的积分记录", businessType = BusinessType.UPDATE)
    @RepeatSubmit
    @PutMapping()
    public AjaxResult<Void> edit(@Validated(EditGroup.class) @RequestBody UserIntegralRecord userIntegralRecord) {
        return toAjax(userIntegralRecordService.updateById(userIntegralRecord) ? 1 : 0);
    }

    /**
     * 删除用户的积分记录
     */
    @ApiOperation("删除用户的积分记录")
    @PreAuthorize("@ss.hasPermi('module:integralrecord:remove')")
    @Log(title = "用户的积分记录" , businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult<Void> remove(@NotEmpty(message = "主键不能为空") @PathVariable Long[] ids) {
        return toAjax(userIntegralRecordService.removeByIds(Arrays.asList(ids)) ? 1 : 0);
    }
}
